<template>
 <div class="e-form">
    <BillTop @cancel="handleClose"></BillTop>
    <div class="tabs warningTabs">
        <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
            <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag">
            </el-tab-pane>
            <el-tab-pane label="主体信息" name="mainInfo" :disabled="clickTabFlag">
            </el-tab-pane>
            <el-tab-pane label="设备明细" name="contractList" :disabled="clickTabFlag">
            </el-tab-pane>
            <el-tab-pane label="合同条款" name="contractTerms" :disabled="clickTabFlag">
            </el-tab-pane>
            <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag">
            </el-tab-pane>
            <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag">
            </el-tab-pane>
            <el-tab-pane label="签订记录" name="signLog" :disabled="clickTabFlag">
            </el-tab-pane>
            <el-tab-pane label="变更历史" name="changeLog" :disabled="clickTabFlag">
            </el-tab-pane>
            <el-tab-pane label="终止记录" name="terminationLog" :disabled="clickTabFlag">
            </el-tab-pane>
            <div>
                <!-- 基本信息 -->
                <div id="baseInfCon" class="con">
                    <div class="tabs-title" id="baseInfo">基本信息</div>
                    <div style="width: 100%" class="form">
                        <el-form
                            :model="formData"
                            :label-width="formLabelWidth"
                            :rules="{}"
                            ref="rulesBase"
                            class="demo-ruleForm"
                        >
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="合同编号：">
                                        <span>{{
                                            formData.contractNumber
                                        }}</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="所属机构：">
                                        <span>{{ formData.orgName }}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item
                                        label="合同名称："
                                        prop="contractName"
                                    >
                                        <span>{{ formData.contractName }}</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="币种：" prop="currencyId">
                                        <span>{{ formData.currencyName }}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="不含税金额(元)：">
                                        <span>{{
                                            formData.taxExcludedAmount
                                        }}</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item
                                        label="税率%："
                                        prop="taxRate"
                                    >
                                        <span>{{formData.taxRate}}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="税额(元)：">
                                        <span>{{formData.taxAmount}}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="合同金额(元)：">
                                        <span>{{
                                            formData.contractAmount
                                        }}</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="申请状态：">
                                        <span>{{state.find(x=>x.value === formData.state).label}}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row  v-if="formData.contractState >= 4">
                                <el-col :span="12">
                                    <el-form-item label="签订地点：">
                                        <span> {{  showAddress(formData.address) }}</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="签约人：" prop="signingName">
                                            <span>{{
                                            formData.signingName
                                        }}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row  v-if="formData.contractState >= 4">
                                <el-col :span="12">
                                    <el-form-item label="合同有效期：" prop="signingStartTime">
                                        <span>{{formData.signingStartTime + ' - ' + formData.signingEndTime}}</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="签订日期：">
                                        <span>{{formData.signingDate}}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="24">
                                    <el-form-item label="备注：">
                                        <span>{{formData.contractContext}}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="经办人：">
                                        <span>{{ formData.founderName }}</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="录入日期：">
                                        <span>{{formData.gmtCreate}}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col :span="12" v-if="formData.contractState >= 4">
                                    <el-form-item label="本位币：">
                                        <span>{{formData.baseCurName}}</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="变更次数：">
                                        <span>{{formData.period}}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                    <el-col :span="12">
                                    <el-form-item label="合同状态：">
                                        <span>{{
                                            options.stateArr[
                                                formData.contractState
                                            ]
                                        }}</span>
                                    </el-form-item>
                                </el-col>
                                    <el-col :span="12">
                                    <el-form-item label="传输财务共享：" v-if="formData.contractState >= 4">
                                        <span class="redFont" v-if="formData.financialSharing === 0 || formData.financialSharing === 1 || formData.financialSharing === 2 || formData.financialSharing === 4">{{ financialSharingList[formData.financialSharing] }}</span>
                                        <span class="greenFont" v-if="formData.financialSharing === 3 || formData.financialSharing === 5">{{ financialSharingList[formData.financialSharing] }}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row v-if="formData.contractState >= 4">
                                    <el-col :span="12">
                                        <el-col :span="12">
                                            <el-form-item label="本位币汇率：" prop="baseCurRate">
                                                <span>{{formData.baseCurRate}}</span>
                                            </el-form-item>
                                        </el-col>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="人民币汇率：">
                                            <span>{{formData.rmbRate}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            <el-row v-if="formData.state === 5">
                                <el-col :span="12">
                                    <el-col :span="12">
                                        <el-form-item label="作废人：">
                                            <span>{{ formData.nullifyCreator }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="作废时间：">
                                        <span>{{ formData.nullifyCreated }}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row v-if="formData.state === 5">
                                <el-col :span="12">
                                    <el-col :span="12">
                                        <el-form-item label="作废原因：">
                                            <span>{{ formData.nullifyReason }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="作废说明：">
                                        <span>{{ formData.nullifyDescription }}</span>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div>
                </div>

                <!-- 主体信息 -->
                    <SubjectInformation ref="rulesMain" v-model="mainInfo" :formData="formData" :contractListTable="contractListTable" :isView="true" biddingPath="machineBiddingApplicationEdit"></SubjectInformation>

                <!-- 合同清单 审核可以修改-->
                <div id="contractListCon" class="con">
                    <div class="tabs-title" id="contractList">设备明细</div>
                    <MaterialList  ref="MaterialList" v-model="contractListTable"  :billid="billid" :mainInfo="mainInfo" :errorMsg='errorContractMsg'  :auditState="auditState" :isAdd="false" :isEdit="formData.state === 1" @isMonitorTaxRate="isMonitorTaxRate = true" :subcontract="subcontract" :state="formData.state" :formData="formData"></MaterialList>
                </div>

                <!-- 合同条款 暂时未定-->
                <div id="contractTermsCon" class="con">
                    <div class="tabs-title" id="contractTerms">合同条款</div>
                    <!-- <div class="e-table" >
                        <div class="mainTitle">通用合同条款</div>
                        <div class="top">
                            <div class="left">
                                <div>
                                    <el-button size="small" type="primary" plain>选择模板</el-button>
                                </div>
                            </div>
                        </div>
                        <el-table
                            :data="tableData1"
                            border=""
                            style="width: 100%; margin-bottom: 20px"
                        >
                            <el-table-column prop="templateCode" label="模板编号" width="100">
                            </el-table-column>
                            <el-table-column prop="mechanism" label="所属机构" width="250">
                            </el-table-column>
                            <el-table-column prop="clauseTemplate" label="通用条款模板名称" width="270">
                            </el-table-column>
                            <el-table-column prop="" label="条款明细查阅" width="200">
                            </el-table-column>
                            <el-table-column  label="操作" width="200">
                            </el-table-column>
                        </el-table>
                    </div>
                    <div class="e-table" >
                        <div class="mainTitle">项目专用合同条款</div>
                        <div class="top">
                            <div class="left">
                                <div>
                                    <el-button size="small" type="primary" plain>选择条目</el-button>
                                </div>
                            </div>
                        </div>
                        <el-table
                            :data="tableData1"
                            border
                            style="width: 100%; margin-bottom: 20px"
                        >
                            <el-table-column prop="entryCode" label="条目编号" width="100">
                            </el-table-column>
                            <el-table-column prop="" label="名称" width="250">
                            </el-table-column>
                            <el-table-column prop="" label="原条目内容" >
                            </el-table-column>
                        </el-table>
                    </div> -->
                </div>

                <!-- 附件信息 -->
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp
                            :relationId="attachId"
                            bucketName="subcontract"
                            isView
                        />
                    </div>

                 <!-- 审核历史 -->
                <div id="auditHistoryCon" class="con">
                    <div class="tabs-title" id="auditHistory">审核历史</div>
                    <AuditHistoryIndex :billType="7059"></AuditHistoryIndex>
                </div>

                <!-- 签订记录 -->
                <div id="signLogCon" class="con">
                    <div class="tabs-title" id="signLog">签订记录</div>
                    <div class="e-table">
                        <el-table
                            :data="signLogTable" ref="signLogTable" v-sortTable="{ 'tableData': signLogTable, '_this': this, 'ref': 'signLogTable' }"
                            border
                            style="width: 100%"
                            class="table"
                        >
                            <el-table-column prop="signingDate" label="签订日期" width="300">
                            </el-table-column>
                            <el-table-column prop="financialSharing" label="传输财务共享" min-width="300" class-name="blue-column">
                                <template slot-scope="{ row }">
                                    <span  @click="changeSignLog(row)">{{ row.financialSharing>=0 ? financialSharingList[row.financialSharing]:'' }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="founderName" label="经办人"  width="300">
                            </el-table-column>
                        </el-table>
                    </div>
                </div>

               <!-- 变更历史 -->
                <div id="changeLogCon" class="con">
                    <div class="tabs-title" id="changeLog">变更历史</div>
                    <div class="e-table" >
                        <el-table
                            :data="changeLogTable" ref="changeLogTable" v-sortTable="{ 'tableData': changeLogTable, '_this': this, 'ref': 'changeLogTable' }"
                            border
                            style="width: 100%"
                            class="table"
                        >
                            <el-table-column prop="changeNumber" label="变更编号" min-width="200" class-name="blue-column">
                                <template slot-scope="{ row }">
                                    <span  @click="changeLog(row)">{{ row.changeNumber }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="period" label="变更期数" width="200">
                            </el-table-column>
                            <el-table-column prop="originalContractAmount" label="原合同金额" width="130">
                            </el-table-column>
                            <el-table-column prop="changeAmount" label="变更金额"  width="120">
                            </el-table-column>
                            <el-table-column prop="amountAfterChange" label="变更后金额"  width="130">
                            </el-table-column>
                            <el-table-column prop="changeTime" label="变更日期"  width="130">
                                <template slot-scope="{ row }">
                                    <span v-if="row.period !== 0">{{ row.changeTime }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="state" label="状态"  width="120">
                                <template slot-scope="{ row }">
                                    <span v-if="row.period !== 0">{{state.find(x=>x.value === row.state).label}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="financialSharing" label="传输财务共享">
                                <template slot-scope="{ row }">
                                    <span v-if="row.period !== 0">{{ row.financialSharing>=0 ? financialSharingList[row.financialSharing]:'' }}</span>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>

                <!-- 终止记录 -->
                <div id="terminationLogCon" class="con">
                    <div class="tabs-title" id="terminationLog">终止记录</div>
                    <div class="e-table">
                         <el-table
                            :data="terminationLogTable" ref="terminationLogTable" v-sortTable="{ 'tableData': terminationLogTable, '_this': this, 'ref': 'terminationLogTable' }"
                            border
                            style="width: 100%"
                            class="table"
                            :row-dbclick="changeTerminationLog"
                        >
                            <el-table-column prop="stopDate" label="终止生效日期" width="200">
                            </el-table-column>
                            <el-table-column prop="approvedTime" label="审核通过日期" width="200">
                            </el-table-column>
                            <el-table-column
                                    prop="founderName"
                                    label="经办人"
                                    width="200"
                                >
                            </el-table-column>
                            <el-table-column prop="terminationStatus" label="状态"  class-name="blue-column">
                                <template slot-scope="{ row }">
                                    <span  @click="changeTerminationLog(row)">{{ state.find(x=>x.value === row.state).label}}</span>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </div>
        </el-tabs>
    </div>
    <div class="buttons" v-if="!isview">
        <el-button type="primary" v-if="formData.contractState === 2" v-permission="['edit']" class="btn-blue" @click="goSigningPage"
            >合同签订</el-button
        >
        <el-button type="primary" v-if="formData.contractState === 4 " v-permission="['edit']" class="btn-blue" @click="goCtChangePage"
            >合同变更</el-button
        >
        <el-button type="primary" v-if="formData.contractState === 2 || formData.contractState === 4 || formData.contractState === 6" v-permission="['edit']" class="btn-blue" @click="goCtEndPage"
            >合同终止</el-button
        >
        <ComExaButtons :auditState="auditState" :state="formData.state" @exas="exas" :founderId="formData.founderId" />
        <el-button @click="handleClose">取消</el-button>
    </div>
    <div id="seat" :style="{height: seatHeight + 'px'}"></div>
 </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapState, mapMutations } from 'vuex'
import fn from '@/utils/checkEmpty.js'
import AttachComp from '@/components/common/attachIndex'
import ComExaButtons from '@/components/common/exaButtons'
import count from '@/utils/contractCount.js'
import equimentLeaseIncomeApply from '@/api/balanceContractApi/equimentLeaseIncomeApi/equimentLeaseIncomeApply.js'
import auditRequest from '@/api/subcontractApi/audit.js'
import { getRmbRate } from '@/api/equip/common.js'
import MaterialList from '@/pages/balanceContract/equipmentIncome/equimentLeaseIncomeContract/publicList/materialList.vue'
import $ from 'jquery'
import {  selectDataClient, showLoading, hideLoading, throttle } from '@/utils/common'
import AuditHistoryIndex from '@/pages/subcontract/components/auditHistory/auditHistoryIndex.vue'
import SubjectInformation from '@/pages/balanceContract/equipmentIncome/equimentLeaseIncomeContract/components/subjectInformation.vue'
import { exas, saveAll, submitCommit } from '@/pages/subcontract/common/contractCom.js'
export default {
    data () {
        return {
            //基本信息表单数据
            formData: {
                'address': '',
                'advanceCharge': 0,
                'baseCurId': '',
                'baseCurName': '',
                'baseCurRate': 0,
                'billId': '',
                'bondAmount': 0,
                'bondState': true,
                'contractAmount': 0,
                'contractChangeAmount': 0,
                'contractContext': '',
                'contractName': '',
                'contractNumber': '',
                'contractState': 0,
                'currencyId': '',
                'currencyName': '',
                'financialSharing': 0,
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'period': 0,
                'rmbName': '',
                'rmbRate': 0,
                'serverType': 0,
                'signingDate': '',
                'signingEndTime': '',
                'signingId': '',
                'signingName': '',
                'signingStartTime': '',
                'state': 0,
                'taxAmount': 0,
                'taxExcludedAmount': 0,
                'taxRate': 0,
                'serverUnitAmount': 0,
                'workId': ''
            },
            //主体信息表单数据
            mainInfo: {
                secondParty: {
                    'accountNumber': '',
                    'address': '',
                    'bankName': '',
                    'billId': '',
                    'fax': '',
                    'legalRepresentative': '',
                    'orgId': '',
                    'orgName': '',
                    'phone': '',
                    'postalCode': '',
                    'principalAgent': '',
                    'principalAgentPhone': '',
                    'socialCode': '',
                    'sourceId': this.$route.query.billid,
                },
                notarization: {
                    'accountNumber': '',
                    'bankName': '',
                    'billId': '',
                    'name': '',
                    'notaryTime': null,
                    'opinion': '',
                    'sourceId': this.$route.query.billid,
                },
                firstParty: {
                    'accountNumber': '',
                    'address': '',
                    'anotherName': '',
                    'bankName': '',
                    'biddingId': '',
                    'biddingName': '',
                    'billId': '',
                    'dtlId': '',
                    'fax': '',
                    'legalRepresentative': '',
                    'name': '',
                    'phone': '',
                    'postalCode': '',
                    'principalAgent': '',
                    'principalAgentPhone': '',
                    'socialCode': '',
                    'outerTypeValue': '',
                    'sourceId': this.$route.query.billid,
                }
            },
            formLabelWidth: '195px',
            ctsubcontractId: '', //合同id
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
 	        winEvent: {},
            errorList: [], //控制导航栏感叹号的显示
            contractListTable: [], //合同清单表格数据
            serviceListTable: [], //服务清单表格数据
            commonCtTermsTable: [], //通用合同条款表格数据
            onlyCtTermsTable: [], //项目专用合同条款表格数据
            attachTable: [], //附件信息表格数据
            auditHistoryTable: [], //审核历史表格数据
            signLogTable: [], //签订记录表格数据
            changeLogTable: [], //变更记录表格数据
            settlementParameterTable: [], //结算台账表格数据
            terminationLogTable: [], //终止记录表格数据
            objFlag: {
                //判断是否转圈圈
                flag1: false,
                flag2: false,
                flag3: false,
                flag4: false,
                flag5: false,
                flag6: false,
                flag7: false,
                flag8: false,
                flag9: false,
                flag10: false,
                flag11: false,
                flag12: false
            },
            billid: this.$route.query.billid,
            rulesBase: {},
            rulesMain: {},
            disabled: false, //是否禁止
            auditState: {}, //流程按钮显示状态
            auditParams: {
                'billId': this.$route.query.billid,
                'billType': 7059
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 7059,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: ''
            },
            isContructSearchKey: false,
            errorContractMsg: [],
            errorServiceMsg: [],
            isMonitorTaxRate: false, //是否计算税率
            subcontract: null, //当前页面的api
            isview: false, //是否隐藏底部按钮
            leaseTypeList: [
                { value: 0, label: '外租' },
                { value: 2, label: '临租' },
            ]
        }
    },
    components: {
        AttachComp,
        AuditHistoryIndex,
        MaterialList,
        ComExaButtons,
        SubjectInformation
    },
    created () {
        this.init()
        this.subcontract = equimentLeaseIncomeApply
        if(this.$route.query.isview === 'true' || this.$route.query.isview === 'false') {
            this.isview = JSON.parse(this.$route.query.isview)
        }
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()
        // 保存所有tabName
        const arr = [
            'baseInfo',
            'mainInfo',
            'contractList',
            'contractTerms',
            'attach',
            'auditHistory',
            'signLog',
            'changeLog',
            'terminationLog'
        ]
        this.tabArr = arr
        let $idsTop = []
        const onScroll = () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        }
        this.winEvent.onScroll = onScroll
        window.addEventListener('scroll', this.winEvent.onScroll)
        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        const onResize = () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        }
        this.winEvent.onResize = throttle(onResize, 500)
        window.addEventListener('resize', this.winEvent.onResize)
        if(this.$route.query.name) {
            setTimeout(()=>{
                this.onChangeTab({
                    name: this.$route.query.name
                })
                this.tabsName = this.$route.query.name
            }, 200)
        }
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.winEvent.onScroll)
        window.removeEventListener('resize', this.winEvent.onResize)
    },
    computed: {
        ...mapState({
            options: state => state.contract.ctClassify,
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            financialSharingList: state => state.contract.ctClassify.financialSharingList, //传输财务共享
            state: state => state.equip.equipData.state, //通用流程状态
        }),
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.$route.query.billid
        },
        //是否是从招标引入 true招标false目标预算
        isBidding () {
            return this.mainInfo.secondParty.biddingId ? true : false
        },
        showAddress () {
            return value=>{
                if(!value) return ''
                try {
                    let obj = JSON.parse(value)
                    const  address = obj.address ? obj.address.join('-') : ''
                    const  detail = obj.detail
                    let str = ''
                    if(address && detail) {
                        str = address + '-' + detail
                    }else if(!address  && detail) {
                        str = detail
                    }else if(address  && !detail) {
                        str = address
                    }
                    return str
                }
                catch(err) {
                    return value
                }

            }
        }
    },
    watch: {
        contractListTable: {
            handler (newData) {
                if(this.isMonitorTaxRate) {
                    if(newData.length > 0) {
                        let num = 0
                        newData.forEach(item=>{
                            if(item.changeType !== -1)num += parseFloat(item.amount)
                        })
                        this.formData.taxExcludedAmount = num.toFixed(2)
                    }else{
                        this.formData.taxExcludedAmount = 0
                    }
                    this.monitorTaxRate()
                }
            },
            deep: true
        },
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    methods: {
        ...mapMutations(['setAuditParams']),
        ...mapMutations(['setSelectedInfo']),
        //初始化数据
        init () {
            showLoading()
            Promise.all([
                this.getBasic(),
                this.getMain(),
                this.getContractTerms(),
                this.getAttach(),
                this.getAuditHistory(),
                this.getsignLog(),
                this.getChangeLog(),
                this.getSettlementParameter(),
                this.getTerminationLog(),
                this.getCurrentUnitInfo()  //获取流程按钮显示状态
            ]).finally(() => {
                hideLoading()
            })
        },
        //获取流程按钮显示状态
        getCurrentUnitInfo () {
            if(this.formData.state !== -1 && this.formData.state !== 2 && this.formData.state !== 5) {
                auditRequest.getUnitInfoByBillId(this.auditParams).then(res => {
                    this.auditState = res
                })
            }
        },
        handleCurrency (val) {
            this.formData.currencyName = this.currencyForm.find(x=>x.value === val).label
            if(this.formData.currencyName === '人民币') {
                this.formData.rmbRate = 1
            }else{
                getRmbRate({
                    currency: val,
                    orgId: this.userInfo.orgInfo.orgId
                }).then(res=>{
                    this.formData.rmbRate = res.rate
                })
            }
            if(this.formData.currencyId === this.formData.baseCurId) {
                this.formData.scRate = 1
                this.showBaseCurName = false
            }else{
                this.showBaseCurName = true
            }
        },
        //取消
        handleClose () {
            hideLoading()
            this.$router.replace('/equimentLeaseIncomeContract')
        },
        //判断主体信息或合同清单是否存在数据
        test () {
            //有数据为 true
            this.flag1 = !this.checkEmpty(this.mainInfo.secondParty)
            this.flag2 = !this.checkEmpty(this.mainInfo.notarization)
            this.flag3 = !this.checkEmpty(this.mainInfo.firstParty)
            this.flag4 = !this.checkEmpty(this.contractListTable)
        },
        //计算
        count () {
            //计算税额 税额=税率*不含税金额 + 服务清单金额*服务费税率
            this.formData.taxAmount = count.equipmentTaxRate(this.contractListTable, this.serviceListTable, this.formData.taxRate, this.formData.transportTaxRate)
            //计算合同金额 合同金额=不含税金额+税额+服务单位费用
            this.formData.contractAmount = count.materialstMoney(
                this.formData.taxExcludedAmount,
                this.formData.taxAmount,
                this.formData.serverUnitAmount
            )
            //计算预付款比例 预付款比例=预付款金额/合同金额*100%
            this.formData.advanceChargeProportion = count.countRatio(
                +this.formData.advanceCharge,
                this.formData.contractAmount
            )
        },
        //监听税率
        monitorTaxRate () {
            this.count()
        },
        //监听税额
        monitorTax () {
            this.formData.contractAmount = count.materialstMoney(
                this.formData.taxExcludedAmount,
                this.formData.taxAmount,
                this.formData.serverUnitAmount
            )
            this.formData.advanceChargeProportion = count.countRatio(
                +this.formData.advanceCharge,
                this.formData.contractAmount
            )
        },
        //监听预付款金额
        monitorMoney () {
            this.formData.contractAmount = count.materialstMoney(
                this.formData.taxExcludedAmount,
                this.formData.taxAmount,
                this.formData.serverUnitAmount
            )
            this.formData.advanceChargeProportion = count.countRatio(
                +this.formData.advanceCharge,
                this.formData.contractAmount
            )
        },
        //验证邮政编码
        postalCodeTest (rule, value, callback) {
            if (value === undefined || value === '' || value === null) {
                callback()
            }
            if (value.length == 6) {
                callback()
            } else {
                callback(new Error('请输入6位数'))
            }
        },
        //验证电话号码
        phoneTest (rule, value, callback) {
            const require = this.rulesMain[rule.field][0].required
            const reg = /^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/
            if (reg.test(value)) {
                callback()
            }else if(!value && !require) {
                callback()
            }
            else {
                callback(new Error('请输入有效电话'))
            }
        },
        //验证法人代表
        textLen (rule, value, callback) {
            if (value.length < 20) {
                callback()
            } else {
                callback(new Error('不能超过20个字'))
            }
        },
        //判断数据是否为空
        checkEmpty (datas) {
            return fn.checkEmpty(datas)
        },
        //根据id查询基础信息
        getBasic () {
            this.isMonitorTaxRate = false
            equimentLeaseIncomeApply.getInfo(this.billid).then(res => {
                this.formData = res
                const { baseCyByOrgId } = this.userInfo
                this.formData.baseCurName = baseCyByOrgId.currencyName  //本位币
                this.formData.baseCurId = baseCyByOrgId.currency
                //this.count()
            })
        },
        //根据id查询主体信息
        getMain () {
            equimentLeaseIncomeApply.getMainstay(this.billid).then(res => {
                const fn = feild=>{
                    if(res[feild]) {
                        for(let key in res[feild]) {
                            this.mainInfo[feild][key] = res[feild][key]
                        }
                    }
                }
                fn('secondParty')
                fn('notarization')
                fn('firstParty')
                if(!this.mainInfo.secondParty.orgId) {
                    this.mainInfo.secondParty.orgId = this.userInfo.orgInfo.orgId
                    this.mainInfo.secondParty.orgName = this.userInfo.orgInfo.orgName
                }
                this.mainInfo.secondParty.sourceId = this.mainInfo.secondParty.sourceId ? this.mainInfo.secondParty.sourceId : this.billid
                this.mainInfo.notarization.sourceId = this.mainInfo.notarization.sourceId ? this.mainInfo.notarization.sourceId : this.billid
                this.mainInfo.firstParty.sourceId = this.mainInfo.firstParty.sourceId ? this.mainInfo.firstParty.sourceId : this.billid
                this.test()
            })
        },
        //根据id查询合同清单
        getContractList () {
            this.$refs['MaterialList'].getData()
        },
        //根据id查询服务清单
        getServiceList () {
            this.$refs['ServiceList'].getData()
        },

        //根据id查询保证金
        getEarnestMoney () {
            this.$refs['Bond'].getData()
        },
        //根据id查询合同条款
        getContractTerms () {
            this.objFlag.flag6 = true
        },
        //根据id查询附件信息
        getAttach () {
            this.objFlag.flag7 = true
        },
        //根据id查询审核历史
        getAuditHistory () {
            this.objFlag.flag8 = true
        },
        //根据id查询签订记录
        getsignLog () {
            equimentLeaseIncomeApply.findBySigningRecord({
                originalBillId: this.billid
            }).then(res=>{
                this.signLogTable = res.data === null ? [] : [res]
            })
        },
        //根据id查询变更记录
        getChangeLog () {
            equimentLeaseIncomeApply.getChangeRecords({
                originalBillId: this.billid
            }).then(res=>{
                this.changeLogTable = res.data === null ? [] : res
            })
        },
        //根据id查询结算台账
        getSettlementParameter () {
            this.objFlag.flag11 = true
        },
        //根据id查询终止记录
        getTerminationLog () {
            equimentLeaseIncomeApply.getStopRecord({
                sourceId: this.billid
            }).then(res=>{
                this.terminationLogTable = res.data === null ? [] : res
            })
        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                this.$refs.rulesBase.validate(valid => {
                    if (valid) {
                        equimentLeaseIncomeApply.createInfo(this.formData).then(() => {
                            this.clearError('baseInfo')
                            resolve()
                            this.getBasic()
                        }).catch(err=>{
                            reject(err)
                            this.setError('baseInfo')
                        })
                    } else {
                        this.setError('baseInfo')
                        reject('基本信息错误')
                    }
                })
            })

        },

        //新增(修改)主体信息
        createMainInfo () {
            return new Promise((resolve, reject)=>{
                const { rulesMain } = this.$refs.rulesMain.$refs
                rulesMain.validate(valid => {
                    if (valid) {
                        equimentLeaseIncomeApply.createMainstay(this.mainInfo).then(() => {
                            this.str = JSON.stringify(this.mainInfo)
                            this.clearError('mainInfo')
                            resolve()
                            this.getMain()
                        }).catch(err=>{
                            this.setError('mainInfo')
                            reject(err)
                        })
                    } else {
                        this.setError('mainInfo')
                        reject('主体信息错误')
                    }
                })
            })
        },
        //删除基本信息
        deleteBaseInfo () {
            this.clientPop(
                'info',
                this.oneDeleteErr,
                ()=>{
                    showLoading()
                    equimentLeaseIncomeApply.deleteInfo(this.billid).then(() => {
                        hideLoading()
                        this.clientPop('suc', '删除成功', this.handleClose)
                    })
                }
            )
        },

        //保存清单
        saveContractList (isComit = false) {
            return new Promise((resolve, reject)=>{
                let contractListTable = [...this.contractListTable]
                if(isComit) {
                    const filterData = contractListTable.filter(x=>x.changeType !== -1)
                    if(filterData.length === 0) {
                        this.setError('contractList')
                        reject('必须引入清单')
                        return
                    }
                    else{
                        this.errorContractMsg = []
                        filterData.forEach(item=>{
                            !item.unitPrice > 0 ? this.setErrorContractMsg('请填写单价') : ''
                            !item.timingUnitId ? this.setErrorContractMsg('请选择计时单位') : ''
                            !item.leaseTerm > 0 ? this.setErrorContractMsg('请填写租期') : ''
                            if(this.formData.biddingId && (item.unitPrice > item.oriUnitPrice) && item.oriUnitPrice) this.setErrorContractMsg('不能超过招标清单单机租金')
                            if(this.formData.biddingId && (item.leaseTerm > item.oriLeaseTerm) && item.oriLeaseTerm !== '') this.setErrorContractMsg('不能超过招标清单租期')
                        })
                        if(this.errorContractMsg.length > 0) {
                            this.setError('contractList')
                            reject('合同清单错误')
                            return
                        }else{
                            this.clearError('contractList')
                        }
                    }

                }else{
                    if(contractListTable.length === 0) {
                        resolve()
                        return
                    }
                }
                const filterData = contractListTable.filter(x=>x.changeType !== 0)
                const newListAll =  filterData.map(x=>{
                    const obj = {
                        'amount': 0,
                        'amountAfterChange': 0,
                        'amountUpdateFlag': true,
                        'billId': '',
                        'changeState': 0,
                        'changeType': 0,
                        'equipmentName': '',
                        'equipmentNumber': '',
                        'leaseTerm': '',
                        'leaseTermAfterChange': '',
                        'leaseTermUpdateFlag': true,
                        'oriBillId': '',
                        'oriLeaseTerm': '',
                        'oriQuantity': 0,
                        'oriUnitPrice': 0,
                        'quantity': 0,
                        'sourceId': '',
                        'specificationModel': '',
                        'timingUnit': '',
                        'timingUnitId': '',
                        'unit': '',
                        'unitPrice': 0,
                        'unitPriceAfterChange': 0,
                        'unitPriceUpdateFlag': true
                    }
                    for(let key in obj) {
                        obj[key] = x[key] !== undefined ? x[key] : obj[key]
                    }
                    return obj
                })
                if(newListAll.length === 0) {
                    resolve()
                    return false
                }
                equimentLeaseIncomeApply.saveList(newListAll).then(()=>{
                    this.clearError('contractList')
                    resolve()
                    this.getContractList()
                }).catch(err=>{
                    this.setError('contractList')
                    reject(err)
                })
            })

        },
        //先保存乙方信息 再保存合同清单 再保存物资清单 再报错基本信息
        saveMianList (isComit = false) {
            return new Promise((resolve, reject)=>{
                this.saveContractList(isComit).then(()=>{
                    this.updateBaseInfo().then(()=>{
                        resolve()
                    }).catch(err=>{
                        reject(err)
                    })
                }).catch(err=>{
                    reject(err)
                })

            })
        },
        setErrorContractMsg (msg) {
            let index = this.errorContractMsg.findIndex(x=>x === msg)
            if(index === -1) {
                this.errorContractMsg.push(msg)
            }
        },
        setErrorServiceMsg (msg) {
            let index = this.errorServiceMsg.findIndex(x=>x === msg)
            if(index === -1) {
                this.errorServiceMsg.push(msg)
            }
        },
        //保存全部数据
        saveAll () {
            const requestFn = ()=>{
                return [
                    this.saveMianList(),
                ]
            }
            saveAll(this, requestFn)
        },
        //保存并提交
        submitCommit () {
            const requestFn = ()=>{
                return [
                    this.saveMianList(true),
                ]
            }
            submitCommit(this, requestFn)
        },
        //保存
        submit () {
            this.saveAll()
        },
        //删除所有信息
        deleteData () {
            this.deleteBaseInfo()
        },
        // 审核相关操作
        async exas (arg) {
            const requestFn = ()=>{
                return [
                    this.saveMianList(true)
                ]
            }
            exas(arg, this, requestFn)
        },
        //去合同签订页面
        goSigningPage () {
            const billid = this.billid
            this.$router.push({
                path: '/equimentLeaseIncomeSigningAdd',
                query: { billid }
            })
        },
        //去合同变更页面
        goCtChangePage () {
            const billid = this.billid
            this.$router.push({
                path: '/equimentLeaseIncomeChangeApplyAdd',
                query: { billid }
            })
        },
        //去合同终止页面
        goCtEndPage () {
            const billid = this.billid
            this.$router.push({
                path: '/equimentLeaseIncomeEndAdd',
                query: { billid, originalBillId: this.billid, sourceState: this.formData.contractState  }
            })
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('terminationLog')) {
                    const lastConHeight =
                        document.getElementById('terminationLog').offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //清除错误标签
        clearError (name) {
            const index = this.errorList.findIndex(x=>x === name)
            if(index !== -1) {
                this.errorList.splice(index, 1)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        //选择本机级上级机构
        selectOrg () {
            selectDataClient({
                SelectServiceToken: '/hr/org/getParentOrg', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                Title: '选择机构' // 标题
            }).then(val => {
                this.mainInfo.secondParty.orgName = val[0].orgName
                this.mainInfo.secondParty.orgId = val[0].orgId
            })
        },
        //跳转到合同签订
        changeSignLog (row) {
            // if(row.financialSharing === 0 || row.financialSharing === 4) {
            //     this.$router.push({
            //         path: '/contractSigningEdit',
            //         query: {
            //             billid: row.billId
            //         }
            //     })
            // }else{
            //     this.$router.push({
            //         path: '/contractSigningShow',
            //         query: {
            //             billid: row.billId
            //         }
            //     })
            // }
            if(row.state === -1 || row.state === 2 || row.state === 5 || !this.permission(['edit'])) {
                this.$router.push({
                    path: '/equimentLeaseIncomeSigningShow',
                    query: { billid: row.billId }
                })
            }else{
                const auditParams = {
                    'billId': row.billId,
                    'billType': 7060
                }
                auditRequest.getUnitInfoByBillId(auditParams).then(res => {
                    if(res.canModify) {
                        this.$router.push({
                            path: '/equimentLeaseIncomeSigningEdit',
                            query: { billid: row.billId }
                        })
                    }else{
                        this.$router.push({
                            path: '/equimentLeaseIncomeSigningShow',
                            query: { billid: row.billId }
                        })
                    }
                })
            }
        },
        //跳转到合同申请变更
        changeLog (row) {
            if(row.period === 0) {
                this.$router.push({
                    path: '/equimentLeaseIncomeChangeApplyShow',
                    query: { billid: row.billId, originalBillId: this.billid, period: row.period }
                })
                return
            }
            if(row.state === -1 || row.state === 2 || row.state === 5 || !this.permission(['edit'])) {
                this.$router.push({
                    path: '/equimentLeaseIncomeChangeApplyShow',
                    query: { billid: row.billId, originalBillId: this.billid, period: row.period }
                })
            }else{
                const auditParams = {
                    'billId': row.billId,
                    'billType': 7061//合同申请变更billType
                }
                auditRequest.getUnitInfoByBillId(auditParams).then(res => {
                    if(res.canModify) {
                        this.$router.push({
                            path: '/equimentLeaseIncomeChangeApplyEdit',
                            query: { billid: row.billId, originalBillId: this.billid, period: row.period  }
                        })
                    }else{
                        this.$router.push({
                            path: '/equimentLeaseIncomeChangeApplyShow',
                            query: { billid: row.billId, originalBillId: this.billid, period: row.period  }
                        })
                    }
                })
            }
        },
        //跳转到合同终止
        changeTerminationLog (row) {
            if(row.state === -1 || row.state === 2 || row.state === 5 || !this.permission(['edit'])) {
                this.$router.push({
                    path: '/equimentLeaseIncomeEndShow',
                    query: { billid: row.billId, originalBillId: this.billid }
                })
            }else{
                const auditParams = {
                    'billId': row.billId,
                    'billType': 7063 //合同终止billType
                }
                auditRequest.getUnitInfoByBillId(auditParams).then(res => {
                    if(res.canModify) {
                        this.$router.push({
                            path: '/equimentLeaseIncomeEndEdit',
                            query: { billid: row.billId, originalBillId: this.billid, sourceState: this.formData.contractState }
                        })
                    }else{
                        this.$router.push({
                            path: '/equimentLeaseIncomeEndShow',
                            query: { billid: row.billId, originalBillId: this.billid, sourceState: this.formData.contractState }
                        })
                    }
                })
            }
        },
    }
}
</script>

<style lang='scss' scoped>
.mainTitle{
    box-sizing: border-box;
    width:100%;
    height: 40px;
    line-height: 40px;
    background: rgb(246,246,246);
    border: 1px solid rgb(236, 236, 236);
    margin: auto;
    margin-bottom: 15px;
    padding-left: 10px;
}
.separ{
   width: 30px;
   height: 40px;
   line-height: 18px;
   text-align: center;
}
.e-table{
    min-height: auto;
    background: #fff;
}

.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}

::v-deep.el-input--suffix .el-input__inner {
    padding-right: 5px;
}

</style>